package com.aimao.blog.service.impl;

import com.aimao.blog.config.CustomUploadConfig;
import com.aimao.blog.constant.ServerResponse;
import com.aimao.blog.service.FileUploadService;
import com.aimao.blog.vo.UploadResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author PuaChen
 * @Create 2018-07-06 12:50
 */
public class LocalFileUploadServiceImpl implements FileUploadService {


    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private CustomUploadConfig customUploadConfig;

    /**
     * 最基础的文件上传
     *
     * @param file
     * @param typeDirectory 要上传的文件夹名称 从常量中获取
     * @param namePrefix    选择性给值 文件的前缀
     * @return 成功后返回的是文件名称地址 可直接存入数据库的
     */
    @Override
    public ServerResponse<UploadResult> upload(MultipartFile file, String typeDirectory, String namePrefix) {
        if (customUploadConfig == null) {
            throw new NullPointerException("配置文件类没有被初始化");
        }
        if (file == null || file.isEmpty()) {
            return ServerResponse.createFailure("参数错误");
        }

        String originalName = file.getOriginalFilename();
        String fileType = originalName.substring(originalName.lastIndexOf("."));
        String newName = UUID.randomUUID().toString().replaceAll("\\W", "");
        if (StringUtils.isNotBlank(namePrefix)) {
            newName = namePrefix + newName;
        }
        newName = newName + fileType;
        File root = new File(customUploadConfig.getDirFilePath());
        //如果目录不存在则创建
        if (!root.exists()) {
            root.setWritable(true);
            root.mkdirs();
        }
        File dest = new File(root, newName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            logger.error("保存文件出现异常", e);
            return ServerResponse.createFailure("文件上传失败");
        } finally {
            logger.info("文件上传信息：文件名：{},文件路径：{}", newName, dest.getAbsolutePath());
        }
        String url = new String(customUploadConfig.getUrl());
        if (!url.endsWith("/")) {
            url = url + "/";
        }
        url = url + newName;
        UploadResult uploadResult = new UploadResult();
        uploadResult.setAbsoluteUrl(url);
        uploadResult.setNewName(newName);
        uploadResult.setOriginalName(originalName);
        logger.info("文件上传成功,{}", url);
        return ServerResponse.createSuccessAndData(uploadResult);
    }
}
